import { useRef, useCallback, useEffect } from 'react';

function useClickOut(onClickOut) {
  const ref = useRef();
  const handleClick = useCallback(
    (e) => {
      if (ref.current && !ref.current.contains(e.target)) {
        onClickOut(e);
      }
    },
    [onClickOut],
  );
  useEffect(() => {
    document.addEventListener('click', handleClick);
    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, [handleClick]);
  return ref;
}

export default useClickOut;
